import { login, register } from '../../api/user';
import { getToken, setToken, removeToken } from '../../components/util/auth';

const user = {
  state: {
    token: getToken(),
    name: ''
  },
  mutations: {
    SET_NAME: (state, name) => {
      state.name = name;
    },
    SET_TOKEN: (state, token) => {
      state.token = token;
    }
  },
  actions: {
    UserLogin({ commit }, data) {
      return new Promise((resolve, reject) => {
        login(data)
          .then(res => {
            console.log(res);
            const model = res.data.model;
            commit('SET_TOKEN', model.token);
            commit('SET_NAME', model.name);
            //setToken(model.token);
            resolve();
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    UserRegister({ commit }, data) {
      return new Promise((resolve, reject) => {
        register(data)
          .then(response => {
            resolve(response.data);
          })
          .catch(error => {
            reject(error);
          });
      });
    }
  }
};

export default user;
